package pl.s7n.paint.commands;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;

import pl.s7n.paint.utils.Utils;

/**
 * An abstract class for transform commands.<br>
 * Extends ResizeCmd, thus it has the two references: to old and new image.
 * 
 * @author 7
 */
public abstract class AbstractTransformCmd extends ResizeCmd {

  /**
   * Initializes the oldImage field, applies the given transform to the oldImage copy, saves it in newImage field.
   * 
   * @param oldImage
   *          image to be transformed
   * @param at
   *          transformation
   * @param flip
   *          if the transform changes orientation of the image
   */
  public AbstractTransformCmd(BufferedImage oldImage, AffineTransform at, boolean flip) {
    super(oldImage, null);

    int newH = flip ? oldImage.getWidth() : oldImage.getHeight();
    int newW = flip ? oldImage.getHeight() : oldImage.getWidth();

    newImage = Utils.defaultImage(newW, newH);
    Graphics2D g2 = newImage.createGraphics();

    Path2D re = new Path2D.Double();
    re.moveTo(oldImage.getWidth(), oldImage.getHeight());

    double[] coo = new double[6];
    re.getPathIterator(at).currentSegment(coo);
    if (coo[0] < 0) {
      AffineTransform att = AffineTransform.getTranslateInstance(-coo[0], 0);
      att.concatenate(at);
      at = att;
    }
    if (coo[1] < 0) {
      AffineTransform att = AffineTransform.getTranslateInstance(0, -coo[1]);
      att.concatenate(at);
      at = att;
    }

    g2.drawImage(oldImage, at, null);
  }

}
